# 1、获取图像的灰度值
# 2、将其写入MIF文件
from ascii import ascii_font
import numpy as np
from PIL import Image


# ASCII码文件是按照两大行（每大行分为8行8列）来排列的
# 第一大行8个字节掩码，每一个字节都是一列数据

# 打开 MIF 文件并写入头部信息
with open('ascii_94_font.mif', 'w') as mif_file:
    mif_file.write(f"DEPTH = 256;\n")  # 存储器深度，即存储的数据数量：256
    mif_file.write("WIDTH = 128;\n")  # 每个数据的位宽：128位
    # 虽然像素值以十进制形式表示，但位宽决定了每个像素值在存储时所占用的二进制位数。位宽的选择通常与灰度级别的数量有关，而不仅仅是数字的表示形式。
    mif_file.write("ADDRESS_RADIX = UNS;\n")  # 地址的进制：UNS
    mif_file.write("DATA_RADIX = HEX;\n")  # 数据的进制：10进制DEC 无符号10进制UNS 2进制BIN 8进制OCT 16进制HEX
    mif_file.write("CONTENT\n")
    mif_file.write("BEGIN\n")

    mif_file.write(f"    [0..31] : {00000000000000000000000000000000};\n")
    addr = 32
    cnt = 0 
    tmp_data = ""
    li = []
    # 遍历图像的每个像素，并将其写入 MIF 文件
    for item in ascii_font:
        li.append(item)
        cnt += 1
        if cnt == 16:
            # 分为两组
            tmp = []
            for i in li:
                li = bin(i)[2:]
                l = len(li)
                for i in range(l, 8):
                    li = "0" + li
                tmp.append(li)
            
            tmp1 = []
            tmp2 = []
            for i in range(8):
                data1 = 0
                for index_1 in range(0, 8):
                    index_v = 7 - index_1
                    data1 += int(tmp[index_1][i]) << (index_v)
                data2 = 0
                for index_2 in range(8, 16):
                    index_1 = 15 - index_2
                    data2 += int(tmp[index_2][i]) << (index_1)
                tmp1.insert(0, data1)
                tmp2.insert(0, data2)
                
            for i in range(8):
                st_tmp = hex(tmp1[i])[2:]
                l_tmp = len(st_tmp)
                for i in range(l_tmp, 2):
                    st_tmp = "0" + st_tmp
                tmp_data = st_tmp + tmp_data
            
            for i in range(8):
                st_tmp = hex(tmp2[i])[2:]
                l_tmp = len(st_tmp)
                for i in range(l_tmp, 2):
                    st_tmp = "0" + st_tmp
                tmp_data = st_tmp + tmp_data
            
            
                
                
            print(len(tmp_data))
            mif_file.write(f"    {addr} : {tmp_data};\n")
            cnt = 0
            addr += 1
            tmp_data = ""
            li = []
    
    print(addr)
    mif_file.write(f"    [{addr}..255] : {00000000000000000000000000000000};\n")
        
        
    
    # 写入 MIF 文件的结尾
    mif_file.write("END;\n")
